$(() => {
  function getCategories() {
    $.ajax({
      type: "post",
      url: "/admin_getAllCategories",
      // data: "data",
      dataType: "json",
      success: function (res) {
        if (res.code == 1) {
          let html = `<option value="all">所有分类</option>`;
          res.data.forEach((e, i) => {
            html += `<option value="${e.id}">${e.name}</option>`;
          });
          $("#category").html(html);
          getPostsByQuery();
        }
      }
    });
  }
  getCategories();

  function getPostsByQuery() {
    let data = {
      currentPage: currentPage,
      pageSize: pageSize,
      category_id: $("#category").val(),
      status: $("#status").val()
    }
    $.ajax({
      type: "post",
      url: "/getPostByQuery",
      data: data,
      dataType: "json",
      success: function (res) {
        console.log(res);
        if (res.code == 1) {
          let html = template('tp', res.data);
          $("tbody").html(html);
          initPagination(res.pageTotal);
        }
      }
    });

  }

  let currentPage = 1;
  let pageSize = 10;
  let buttonCount = 7;

  function initPagination(pageTotal) {
    pageTotal = pageTotal || 10;
    let start = currentPage - Math.floor(buttonCount / 2);
    if (start <= 1) {
      start = 1;
    }
    let end = start + (buttonCount - 1);
    if (end >= pageTotal) {
      end = pageTotal;
      if (start <= 1) {
        start = 1;
      }
    }

    let html = "";
    if (currentPage != 1) {
      html += `<li class="page-item"><a class="page-link" data-page="${currentPage-1}" href="javascript:;">上一页</a></li>`;
    }
    for (let i = start; i <= end; i++) {
      if(i == currentPage){
        html += `<li class="page-item active"><a class="page-link" data-page="${i}" href="javascript:;">${i}</a></li>`;
      }else {
        html += `<li class="page-item"><a class="page-link" data-page="${i}" href="javascript:;">${i}</a></li>`;
      }
      
    }
    if (end != pageTotal) {
      html += `<li class="page-item"><a class="page-link" data-page="${currentPage+1}" href="javascript:;">下一页</a></li>`;
    }

    $(".pagination").html(html);
  }


  $(".pagination").on('click', 'a', function () {
    let index = parseInt($(this).attr('data-page'));
    currentPage = index;
    getPostsByQuery();
  });

  $("#query").on('click', () => {
    currentPage = 1;
    getPostsByQuery();
  });

});